package com.fishingwithme.android.ui.viewmodels

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fishingwithme.android.data.model.SpotInCircleDto
import com.fishingwithme.android.data.repository.FishingRepository
import kotlinx.coroutines.flow.firstOrNull

class CircleSpotsPagingSource(
    private val repository: FishingRepository,
    private val circleId: String
) : PagingSource<Int, SpotInCircleDto>() {

    override fun getRefreshKey(state: PagingState<Int, SpotInCircleDto>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SpotInCircleDto> {
        val page = params.key ?: 1
        return try {
            val response = repository.getCircleSpots(circleId, page, params.loadSize).firstOrNull()
            
            response?.fold(
                onSuccess = { pageResponse ->
                    // Explicitly specify the type to avoid inference issues
                    val data: List<SpotInCircleDto> = pageResponse.records ?: emptyList()
                    val prevKey = if (page == 1) null else page - 1
                    // Improved nextKey calculation using itemCount approach
                    val nextKey = if (data.isNotEmpty() && data.size >= params.loadSize) {
                        page + 1
                    } else {
                        null
                    }
                    LoadResult.Page(
                        data = data,
                        prevKey = prevKey,
                        nextKey = nextKey
                    )
                },
                onFailure = { throwable ->
                    LoadResult.Error(throwable)
                }
            )?: LoadResult.Error(Exception("No data received"))
        } catch (e: Exception) {
            Log.e("CircleSpots", "Exception while loading circle spots", e)
            LoadResult.Error(e)
        }
    }
}